package com.live.dengdengtv.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.live.dengdengtv.R;
import com.live.dengdengtv.bean.AppConstants;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.LoginInfo;
import com.live.dengdengtv.bean.SimpleInfoData;
import com.live.dengdengtv.bean.gson.ConversationCard;
import com.live.dengdengtv.bean.gson.ConversationSp;
import com.live.dengdengtv.bean.gson.CustomMsg;
import com.live.dengdengtv.bean.gson.GUserInfo;
import com.live.dengdengtv.bean.Constants;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.view.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElemType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageListener;
import com.tencent.TIMMessageStatus;
import com.tencent.TIMUserProfile;
import com.tencent.TIMValueCallBack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 */
public class ChatFragment extends BaseFragment implements TIMMessageListener{

    public static final String C2C_ID = "sendId";
    private static final String TAG = "ChatFragment";
    private final int LAST_MESSAGE_NUM = 20;
    private TIMConversation conversation;
    private String relatedId;
    private boolean isChildFrag;
    private ListView listView;
    private ChatAdapter adapter;
    private List<TIMMessage> messageList = new ArrayList<>();
    private EditText input_message_et;
    private Button send_btn;

    public static ChatFragment newInstance(String identify, boolean isChildFrag) {
        ChatFragment fragment = new ChatFragment();
        fragment.conversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C,identify);
        fragment.relatedId = identify;
        fragment.isChildFrag = isChildFrag;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TIMManager.getInstance().addMessageListener(this);
        getConVersation();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.chat_room, container, false);

        RelativeLayout title_rl = (RelativeLayout) view.findViewById(R.id.title_rl);
        if(isChildFrag){
            title_rl.setVisibility(View.VISIBLE);
        }else {
            title_rl.setVisibility(View.GONE);
        }

        listView = (ListView) view.findViewById(R.id.chat_lv);
        adapter = new ChatAdapter();
        listView.setAdapter(adapter);

        input_message_et = (EditText) view.findViewById(R.id.input_message_et);
        //软键盘事件监听
        input_message_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event)  {
                if (actionId== EditorInfo.IME_ACTION_SEND
                        ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)) {
                    String text = input_message_et.getText().toString().trim();
                    if(!TextUtils.isEmpty(text)){
//                        sendMessage(genTextMessage(text));
                        sendMessage(genCustomMessage(text));
                        input_message_et.setText("");
                    }
                    return true;
                }
                return false;
            }
        });
        send_btn = (Button) view.findViewById(R.id.send_btn);
        send_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = input_message_et.getText().toString().trim();
                if(!TextUtils.isEmpty(text)){
                    sendMessage(genCustomMessage(text));
                    input_message_et.setText("");
                }
            }
        });

        getMessage(null);
        return view;
    }
    private ConversationSp conversationSp;
    private ConversationCard currCard;
    private void recordLsatMsg(TIMMessage msg){

        try {
            TIMCustomElem elem = (TIMCustomElem) msg.getElement(0);
            String customText = new String(elem.getData(), "UTF-8");
            CustomMsg customMsg = new Gson().fromJson(customText, CustomMsg.class);
            currCard.lastMsg = customMsg.getActionParam();
            currCard.create_time = System.currentTimeMillis();

            Log.e(TAG,"会话记录 = "+currCard.lastMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private void saveConVersation(){
        SharedPreferences sp = getActivity().getSharedPreferences(AppConstants.SP_CONVERSATIOM, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String conJson = new Gson().toJson(conversationSp,ConversationSp.class);
        editor.putString(AppConstants.KEY_CONVERSATIOM, conJson);
        Log.e(TAG,"会话json = "+conJson);
        Log.e(TAG,"会话json = "+conversationSp.conCardList.size());
        editor.commit();
    }
    private void getConVersation(){
        SharedPreferences sp = getActivity().getSharedPreferences(AppConstants.SP_CONVERSATIOM, Context.MODE_PRIVATE);
        String conJson = sp.getString(AppConstants.KEY_CONVERSATIOM,"");

        if(!TextUtils.isEmpty(conJson)){
            Log.e(TAG,"conJson不为空 ");
            conversationSp = new Gson().fromJson(conJson,ConversationSp.class);
        }else {
            conversationSp = new ConversationSp();
        }

        if(conversationSp.conCardList.size() > 0){
            for(ConversationCard item: conversationSp.conCardList){
                if(item.user_id.equals(relatedId)){
                    currCard = item;
                }
            }
        }

        if(currCard == null){
            Log.e(TAG,"currCard为空 ");

            currCard = new ConversationCard();
            conversationSp.conCardList.add(0,currCard);

            currCard.user_id = relatedId;
            getRelatedUserInfo();
        }
    }


    private void getRelatedUserInfo(){
        HashMap<String,String> params = new HashMap<>();
        params.put("token",AppInfo.TOKEN);
        params.put("phone_type",AppInfo.PHONE_TYPE);
        params.put("phone_system_version",AppInfo.getPhone_app_version());
        params.put("phone_app_version",AppInfo.getPhone_app_version());
        params.put("client_id",AppInfo.getClient_id());
        params.put("user_id",relatedId);
        requestData(NetTaskList.get_userInfo, params,0);
    }
    @Override
    public boolean onResponse(SimpleInfoData response, int id) {
        if(id == 0){
            if(response.result == 0){
                GUserInfo userInfo = new Gson().fromJson(response.data.getAsJsonObject(), GUserInfo.class);
                currCard.faceUrl = userInfo.image_url;
                currCard.nickName = userInfo.nickname;
                currCard.sex = userInfo.sex;
//                currCard.level = userInfo.;
            }
        }
        return false;
    }
    @Override
    public void onPause() {
        super.onPause();
        saveConVersation();
    }


    private FragmentStopLis fragmentStopLis;
    public void setOnStopLis(FragmentStopLis fragmentStopLis){
        this.fragmentStopLis = fragmentStopLis;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        TIMManager.getInstance().removeMessageListener(this);
        if(fragmentStopLis!=null){
            fragmentStopLis.onFragmentStop();
            fragmentStopLis = null;
        }
    }


    private TIMMessage genCustomMessage(String text){
        CustomMsg customMsg = new CustomMsg();
        customMsg.setUserAction(Constants.AVIMCMD_Private_StrangerMsg);
        customMsg.setActionParam(text);
        CustomMsg.CustomUserInfo sendUserInfo = new CustomMsg.CustomUserInfo();
        sendUserInfo.userId = LoginInfo.getInstance().getUserId();
        sendUserInfo.nickName = LoginInfo.getInstance().getUserNickname();
        sendUserInfo.sex = LoginInfo.getInstance().getUserSex();
        sendUserInfo.faceUrl = LoginInfo.getInstance().getAvatarAddress();
        sendUserInfo.selfSign = LoginInfo.getInstance().getUserSign();
        customMsg.setUserInfo(sendUserInfo);
        String msgJson = new Gson().toJson(customMsg);


        TIMMessage msg = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(msgJson.getBytes());
        elem.setDesc("");
        msg.addElement(elem);
        return msg;
    }
    /**
     * 获取聊天记录
     * @param message 最后一条消息
     */
    public void getMessage(@Nullable TIMMessage message){
        conversation.getMessage(LAST_MESSAGE_NUM, message, new TIMValueCallBack<List<TIMMessage>>() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG,"get message error"+s);
            }

            @Override
            public void onSuccess(List<TIMMessage> timMessages) {
                showMessage(timMessages);
            }
        });
    }

    private void showMessage(List<TIMMessage> messages) {
        int newMsgNum = 0;
        for (int i = 0; i < messages.size(); ++i){
            TIMMessage mMessage = messages.get(i);
            if (mMessage == null || mMessage.status() == TIMMessageStatus.HasDeleted) continue;
            if(mMessage.getElement(0).getType() != TIMElemType.Custom) continue;
            ++newMsgNum;
            messageList.add(0, mMessage);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(newMsgNum);
    }
    /**发送消息*/
    private void sendMessage(final TIMMessage message) {
        conversation.sendMessage(message, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int code, String desc) {//发送消息失败
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code含义请参见错误码表
//                onSendMessageFail(code, desc, message);
            }
            @Override
            public void onSuccess(TIMMessage msg) {
                //发送消息成功,消息状态已在sdk中修改，此时只需更新界面
                onSelfNewMessage(msg);
            }
        });
    }

    @Override
    public boolean onNewMessages(List<TIMMessage> list) {
        for (TIMMessage msg: list){
            if (msg.getConversation().getPeer().equals(conversation.getPeer())&&msg.getConversation().getType()==conversation.getType()){
                reFreshListView(msg);
//                TIMTextElem elem = (TIMTextElem) msg.getElement(0);
                //当前聊天界面已读上报，用于多终端登录时未读消息数同步
                readMessages();
                return true;//返回true,其他监听器不再接收此消息
            }
        }
        return false;
    }

    private void onSelfNewMessage(TIMMessage msg) {
        if (msg.getConversation().getPeer().equals(conversation.getPeer())&&msg.getConversation().getType()==conversation.getType()){
            reFreshListView(msg);
            //当前聊天界面已读上报，用于多终端登录时未读消息数同步
            readMessages();
        }
    }


    private void reFreshListView(TIMMessage msg){
        if (msg == null || msg.status() == TIMMessageStatus.HasDeleted) return;
        if(msg.getElement(0).getType() != TIMElemType.Custom) return;
        messageList.add(msg);
        recordLsatMsg(msg);
        adapter.notifyDataSetChanged();
        listView.setSelection(messageList.size()-1);
    }

    /**设置会话为已读*/
    private void readMessages(){
        conversation.setReadMessage();
    }
    private class ChatAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return messageList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView != null) {
                holder = (ViewHolder)convertView.getTag();
            } else {
                convertView = View.inflate(getActivity(), R.layout.chat_item, null);

                holder = new ViewHolder();
                holder.left_panel = (ViewGroup) convertView.findViewById(R.id.left_panel);
                holder.left_msg_tv = (TextView) convertView.findViewById(R.id.left_msg_tv);
                holder.left_head_cv = (CircleImageView) convertView.findViewById(R.id.left_head_cv);

                holder.right_panel = (ViewGroup) convertView.findViewById(R.id.right_panel);
                holder.right_msg_tv = (TextView) convertView.findViewById(R.id.right_msg_tv);
                holder.right_head_cv = (CircleImageView) convertView.findViewById(R.id.right_head_cv);

                convertView.setTag(holder);
            }
            setHolderData(position, holder);
            return convertView;
        }

        private void setHolderData(int position, ViewHolder holder) {
            TIMMessage timMessage = messageList.get(position);
            TIMUserProfile senderProfile = timMessage.getSenderProfile();

            TIMCustomElem elem = (TIMCustomElem) timMessage.getElement(0);

            try {
                String customText = new String(elem.getData(), "UTF-8");
                CustomMsg customMsg = new Gson().fromJson(customText, CustomMsg.class);

                if(timMessage.isSelf()){
                    holder.left_panel.setVisibility(View.GONE);
                    holder.right_panel.setVisibility(View.VISIBLE);

                    holder.right_msg_tv.setText(customMsg.getActionParam());
                    ImageLoader.getInstance().displayImage(LoginInfo.getInstance().getAvatarAddress(), holder.right_head_cv);
                }else {
                    holder.right_panel.setVisibility(View.GONE);
                    holder.left_panel.setVisibility(View.VISIBLE);

                    holder.left_msg_tv.setText(customMsg.getActionParam());
                    String faceUrl = customMsg.getUserInfo().faceUrl;
                    ImageLoader.getInstance().displayImage(faceUrl, holder.left_head_cv);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private static class ViewHolder{
        ViewGroup left_panel;
        TextView left_msg_tv;
        CircleImageView left_head_cv;

        ViewGroup right_panel;
        TextView right_msg_tv;
        CircleImageView right_head_cv;
    }

}
